package com.example.aesdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity {

    private TextView tv_str1,tv_str2;
    private EditText et_text;
    private String key = "eeSvvVtUDLi5lTBHDjCeFw==";
    private String jiamiHOu = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_str1 = (TextView) findViewById(R.id.tv_str1);
        tv_str2 = (TextView) findViewById(R.id.tv_str2);
        et_text = (EditText) findViewById(R.id.et_text);
        et_text.setText("{\"name\":\"testname\",\"userip\":\"127.0.0.1\",\"id\":123456}");

        findViewById(R.id.btn_jia).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                jiamiHOu = encrypt(et_text.getText().toString(), key);
                Log.d("TAG","====加密后====>"+jiamiHOu);
                tv_str1.setText("加密："+jiamiHOu);
            }
        });

        findViewById(R.id.btn_jie).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String jiemi = "";
                jiemi = decrypt(jiamiHOu,key);
                Log.d("TAG","====解密后====>"+jiemi);
                tv_str2.setText("解密："+jiemi);
            }
        });
    }


    //把key进行base64解密AES加密得到byte[] 然后转为16进制
    public String encrypt(String input, String key) {
        byte[] crypted = null;
        try {
//            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            //key进行base64解密
            byte[] keyByte = Base64.decode(key, Base64.DEFAULT);
            SecretKeySpec skey = new SecretKeySpec(keyByte, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        //再次进行Base64加密
//        return new String(Base64.encodeToString(crypted, Base64.DEFAULT));
        //把加密结果byte[]转为16进制
        return bytesToHexString(crypted);
    }

    //首先对key进行base64解密，然后对密文进行转换为16进制byte[]，后进行解密
    public String decrypt(String input, String key){
        byte[] output = null;
        try{
            //对秘钥进行base64解密
            byte[] keyByte = Base64.decode(key, Base64.DEFAULT);
            SecretKeySpec skey = new SecretKeySpec(keyByte, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);

            //进行base64解密
//            output = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
            //密文转为byte[]后进行解密
            output = cipher.doFinal(hexStringToBytes(input));
        }catch(Exception e){
            System.out.println(e.toString());
        }
        return new String(output);
    }

    /**
     * byte[]转换成16进制字符串
     *
     * @param src
     * @return
     */
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 16进制字符串转换为byte[]
     *
     * @param hexString
     * @return
     */
    private byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase().replace(" ", "");
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
